<template>
  <div class="set-exam-page">
    <h2>设置考试</h2>

    <!-- 考试名称 -->
    <div class="section">
      <label>考试名称：</label>
      <el-input
          v-model="examName"
          placeholder="请输入考试名称"
          class="exam-name-input"
      />
    </div>

    <!-- 考试日期选择 -->
    <div class="section">
      <label>选择考试日期：</label>
      <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          class="date-picker"
          @change="onDateOrTimeChange"
      />
    </div>

    <!-- 考试时间选择 -->
    <div class="section">
      <label>选择考试时间：</label>
      <el-radio-group v-model="selectedTime" class="time-selection" @change="onDateOrTimeChange">
        <el-radio-button label="8:00-10:00"></el-radio-button>
        <el-radio-button label="10:00-12:00"></el-radio-button>
        <el-radio-button label="14:00-16:00"></el-radio-button>
        <el-radio-button label="16:00-18:00"></el-radio-button>
      </el-radio-group>
    </div>

    <!-- 教室选择 -->
    <div class="section">
      <label>选择教室：</label>
      <el-select v-model="selectedRoom" placeholder="选择教室" class="room-selection">
        <el-option v-for="room in rooms" :key="room.class_id" :label="`${room.class_id} - 容量: ${room.capacity}`" :value="room">
          {{ room.class_id }} - 容量: {{ room.capacity }}
        </el-option>
      </el-select>

      <!-- 显示选择的教室信息 -->
      <div v-if="selectedRoom" class="room-info">
        <p>教室：{{ selectedRoom.class_id }} - 容量：{{ selectedRoom.capacity }}</p>
      </div>
    </div>

    <!-- 座位顺序选择 -->
    <div class="section">
      <label>座位顺序：</label>
      <el-radio-group v-model="seatOrder" class="seat-order">
        <el-radio-button label="顺序"></el-radio-button>
        <el-radio-button label="随机"></el-radio-button>
      </el-radio-group>
    </div>

    <!-- 上传试卷 -->
    <div class="section">
      <label>上传试卷 (PDF)：</label>
      <el-upload
          ref="upload"
          class="upload-demo"
          drag
          :http-request="customUpload"
          :show-file-list="true"
          :before-upload="beforeUpload"
      >
        <el-button size="small" type="primary">点击上传文件</el-button>
      </el-upload>
    </div>

    <!-- 确认按钮 -->
    <el-button type="primary" @click="submitExamSettings" class="confirm-button">确认设置</el-button>
  </div>
</template>

<script>
import { BASE_URL } from '@/config';
import axios from "axios";

export default {
  data() {
    return {
      examName: '', // 新增的考试名称字段
      selectedDate: null, // 选中的考试日期
      selectedTime: '', // 选中的考试时间
      selectedRoom: null, // 选中的教室
      seatOrder: '顺序', // 座位顺序
      uploadUrl: `${BASE_URL}/api/upload`, // 上传接口的URL
      rooms: [], // 教室列表
      uploadedFile: null, // 保存上传的文件信息
    };
  },
  created() {
    console.log(this.$route.query.course_id);
  },
  methods: {
    // 获取教室列表
    onDateOrTimeChange() {
      if (this.selectedDate && this.selectedTime) {
        const timeMapping = {
          "8:00-10:00": 1,
          "10:00-12:00": 2,
          "14:00-16:00": 3,
          "16:00-18:00": 4,
        };

        const timeCode = timeMapping[this.selectedTime];
        if (timeCode) {
          this.fetchRooms(this.selectedDate, timeCode);
        } else {
          this.$message.error('无法解析选中的时间');
        }
      }
    },
    async fetchRooms(date, time) {
      try {
        const response = await axios.post(`${BASE_URL}/exam/checkClassroom`, {
          date,
          time,
        });
        if (response.data.code === 200) {
          this.rooms = response.data.data;
        } else {
          this.$message.error('获取教室信息失败');
        }
      } catch (error) {
        console.error('教室信息获取失败:', error);
        this.$message.error('教室信息获取失败');
      }
    },

    // 自定义上传方法
    async customUpload({ file, onSuccess, onError }) {
      try {
        const base64Data = await this.readFileAsBase64(file);
        const fileName = file.name;

        const requestData = {
          fileName: fileName,
          file: base64Data.split(',')[1],
          course_id: this.$route.query.course_id,
        };

        const response = await axios.post(`${BASE_URL}/exam/upload`, requestData);

        if (response.data && response.data.code === 200) {
          this.uploadedFile = response.data.data; // 保存文件信息
          this.$message.success('文件上传成功');
          onSuccess(response.data);
        } else {
          this.$message.error('文件上传失败，请检查文件格式');
          onError(new Error('上传失败'));
        }
      } catch (error) {
        console.error('文件上传失败:', error);
        this.$message.error('文件上传请求失败');
        onError(error);
      }
    },

    readFileAsBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          resolve(event.target.result);
        };
        reader.onerror = (error) => {
          reject(error);
        };
        reader.readAsDataURL(file);
      });
    },

    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf';
      if (!isPDF) {
        this.$message.error('上传文件只能是 PDF 格式!');
      }
      return isPDF;
    },

    submitExamSettings() {
      if (!this.selectedDate || !this.selectedTime || !this.selectedRoom || !this.examName || !this.uploadedFile) {
        this.$message.error('请完善考试名称、日期、时间、教室选择和上传文件');
        return;
      }

      let timeCode;
      switch (this.selectedTime) {
        case '8:00-10:00':
          timeCode = 1;
          break;
        case '10:00-12:00':
          timeCode = 2;
          break;
        case '14:00-16:00':
          timeCode = 3;
          break;
        case '16:00-18:00':
          timeCode = 4;
          break;
        default:
          this.$message.error('选择的考试时间无效');
          return;
      }

      let sort;
      switch (this.seatOrder) {
        case '顺序':
          sort = 1;
          break;
        case '随机':
          sort = 2;
          break;
      }

      const examData = {
        course_id: this.$route.query.course_id,
        exam_name: this.examName, // 添加考试名称
        date: this.selectedDate,
        time: timeCode,
        tch_id: null,
        class_id: this.selectedRoom.class_id,
        sort: sort,
        file_id: this.uploadedFile, // 将文件ID添加到考试数据中
      };

      axios.post(`${BASE_URL}/exam/selectClassroom`, examData)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('考试设置成功');
            } else {
              this.$message.error('考试设置失败');
            }
          })
          .catch(error => {
            console.error('考试设置提交失败:', error);
            this.$message.error('考试设置提交失败');
          });
    },
  }
};
</script>

<style scoped>
.set-exam-page {
  padding: 2vw;
  max-width: 90%;
  width: 600px;
  margin: 20px auto;
  border-radius: 8px;
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #f5f5f5;
}

h2 {
  font-size: 2vw;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.section {
  margin-bottom: 1.5vw;
  display: flex;
  flex-direction: column;
}

label {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.8vw;
  font-size: 1.2vw;
}

.exam-name-input {
  font-size: 1.1vw;
}

.date-picker,
.time-selection,
.room-selection,
.seat-order {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 1.1vw;
}

.room-capacity {
  margin-top: 8px;
  color: #666;
  font-size: 1.2vw;
}

.upload-demo {
  margin-top: 8px;
}

.confirm-button {
  display: block;
  width: 100%;
  margin-top: 1.5vw;
  font-weight: 600;
  font-size: 1.1vw;
  padding: 1vw;
}

.room-info {
  margin-top: 10px;
  font-size: 1.2vw;
  color: #333;
}

@media (max-width: 768px) {
  .set-exam-page {
    padding: 5vw;
    width: 100%;
  }

  h2 {
    font-size: 4vw;
  }

  .section {
    margin-bottom: 3vw;
  }

  .date-picker,
  .time-selection,
  .room-selection,
  .seat-order {
    font-size: 3vw;
  }

  .confirm-button {
    font-size: 3vw;
  }
}
</style>
